package com.taotao.sso.service.ipml;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;
import com.taotao.sso.dao.IJedisClient;
import com.taotao.sso.service.IUserService;

/**
 * 用户信息
 * 
 * @author Administrator
 *
 */
@Service
public class UserServiceIpml implements IUserService {

	@Autowired
	private TbUserMapper userMapper;

	@Autowired
	private IJedisClient jedisClient;

	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;

	@Value("${SSO_SESSION_EXPIRE}")
	private Integer SSO_SESSION_EXPIRE;

	/**
	 * 用户信息的可用性检测
	 */
	@Override
	public TaotaoResult checkDate(String param, Integer type) {
		// TODO Auto-generated method stub
		// 可选参数1、2、3分别代表username、phone、email

		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		// 用户名检测
		if (1 == type) {
			criteria.andUsernameEqualTo(param);
			// 手机号检测
		} else if (2 == type) {
			criteria.andPhoneEqualTo(param);
			// 邮箱检测
		} else {
			criteria.andEmailEqualTo(param);
		}
		// 执行查询
		List<TbUser> users = this.userMapper.selectByExample(example);
		if (null != users && !users.isEmpty()) {
			return TaotaoResult.ok(false);
		}
		return TaotaoResult.ok(true);
	}

	/**
	 * 用户注册
	 * 
	 * @return
	 */
	public TaotaoResult addUser(TbUser user) {
		// 完善用户信息
		Date created = new Date();
		user.setCreated(created);
		user.setUpdated(created);
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword()
				.getBytes()));
		// 保存用户
		this.userMapper.insertSelective(user);
		return TaotaoResult.ok();
	}

	/**
	 * 用户登录
	 */
	@Override
	public TaotaoResult userLogin(String username, String password) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		// 通过用户名查找用户
		criteria.andUsernameEqualTo(username);
		TbUser user = null;
		List<TbUser> users = this.userMapper.selectByExample(example);
		if (null != users && !users.isEmpty()) {
			user = users.get(0);
			if (!user.getPassword().equals(
					DigestUtils.md5DigestAsHex(password.getBytes()))) {
				return TaotaoResult.build(400, "用户名或密码错误");
			} else {
				// 将密码设空
				user = users.get(0);
				user.setPassword(null);
				// 使用uuid生成用户的令牌 token
				String token = UUID.randomUUID().toString();
				String jsonStr = JsonUtils.objectToJson(user);
				// 将用户信息保存到redis
				this.jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token,
						jsonStr);
				// 设置过期时间
				this.jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token,
						this.SSO_SESSION_EXPIRE);
				return TaotaoResult.ok(token);
			}
		}
		return TaotaoResult.build(400, "用户名或密码错误");
	}

	/**
	 * 通过token查询用户信息
	 */
	@Override
	public TaotaoResult getUserByToken(String token) {
		// TODO Auto-generated method stub
		// 使用token获取用户信息
		String userStr = this.jedisClient.get(REDIS_USER_SESSION_KEY + ":"
				+ token);
		// 判断token是否存在
		if (StringUtils.isNotBlank(userStr)) {
			// 重置过期时间
			this.jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token,
					this.SSO_SESSION_EXPIRE);
			TbUser user = JsonUtils.jsonToPojo(userStr, TbUser.class);
			return TaotaoResult.ok(user);
		}

		return TaotaoResult.build(400, "设置的token已经过期");

	}

	@Override
	public TaotaoResult logoutByToken(String token) {
		// TODO Auto-generated method stub
		String userStr = this.jedisClient.get(REDIS_USER_SESSION_KEY + ":"
				+ token);
		if (StringUtils.isNotBlank(userStr)) {
			this.jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token);
		}

		return TaotaoResult.ok();
	}
}
